package com.moxiu.browser;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;

import com.moxiu.browser.provider.BrowserContract;

public class SaveBookmarkRunnable implements Runnable {
	
	public static final String REMOVE_THUMBNAIL = "remove_thumbnail";
	public static final String TOUCH_ICON_URL = "touch_icon_url";

	// FIXME: This should be an async task.
    private Message mMessage;
    private Context mContext;
    public SaveBookmarkRunnable(Context ctx, Message msg) {
        mContext = ctx.getApplicationContext();
        mMessage = msg;
    }
    public void run() {
        // Unbundle bookmark data.
        Bundle bundle = mMessage.getData();
        String title = bundle.getString(BrowserContract.Bookmarks.TITLE);
        String url = bundle.getString(BrowserContract.Bookmarks.URL);
        String mTouchIconUrl = bundle.getString(AddBookmarkPage.TOUCH_ICON_URL);
        boolean invalidateThumbnail = bundle.getBoolean(REMOVE_THUMBNAIL);
        Bitmap thumbnail = invalidateThumbnail ? null
                : (Bitmap) bundle.getParcelable(BrowserContract.Bookmarks.THUMBNAIL);
        String touchIconUrl = bundle.getString(TOUCH_ICON_URL);

        // Save to the bookmarks DB.
        try {
            final ContentResolver cr = mContext.getContentResolver();
            Bookmarks.addBookmark(mContext, true, url,
                    title, thumbnail, 0);
            if (touchIconUrl != null) {
                new DownloadTouchIcon(cr, url).execute(mTouchIconUrl);
            }
            mMessage.arg1 = 1;
        } catch (IllegalStateException e) {
            mMessage.arg1 = 0;
        }
        mMessage.sendToTarget();
    }

}
